#include <QDebug>
#include <QFile>
#include <QDir>
#include <QTextCodec>
#include "webclientsocket.h"
#define MAX_REQ_LINE 200
#define WebFileFolderName "www/GeneratedFile/"

WebClientSocket::WebClientSocket(int parID,QString strDefaultPage,QObject *parent) :
    QTcpSocket(parent)
{
    setSocketDescriptor(parID);
    defaultPage=strDefaultPage;
    connect(this,SIGNAL(readyRead()),this,SLOT(slotReadClient()));

    initMembers();
}

void WebClientSocket::slotReadClient()
{
    QByteArray httpHead=readLine(MAX_REQ_LINE);
    httpHead=httpHead.simplified();
    QList <QByteArray> listHead=httpHead.split(' ');

    if(listHead.size()!=3)
        write(structHttpByteArray.replyBadRequest); //BAD Request
    else
        write(getReqFile(listHead.at(1)));

    readAll(); //把数据全部读完，但暂时不作处理
}



QByteArray WebClientSocket::getReqFile(QByteArray URI)
{
    QByteArray httpReply;
    QByteArray httpBody;

    if(URI=="/")
    {
        if(defaultPage=="NodeList")
            URI="nodelist.html"; //默认首页
        else
            URI="index.html";
    }

    URI=URI.fromPercentEncoding(URI);
    URI.prepend(WebFileFolderName); //放置网页的文件夹名

    QFile file(URI);
    if(!file.exists())
    {
        httpReply.append(structStatLine.statusNotFound);
        httpReply.append("\r\n");
        URI="404NotFound.html";
        URI.prepend(WebFileFolderName); //放置网页的文件夹名
        file.setFileName(URI);
    }
    else
    {
        httpReply.append(structStatLine.statusOK);
        httpReply.append("\r\n");
    }

    if(file.open(QIODevice::ReadOnly))
    {
           httpBody=file.readAll();
           if(URI.endsWith("html")||URI.endsWith("html"))
                httpBody = QTextCodec::codecForName("GBK")->toUnicode(httpBody).toUtf8();
    }
    else
    {
        qDebug()<<"File opened failed:"<<file.errorString();
        httpReply.append(structStatLine.statusInternalServerError);
        httpReply.append("\r\n");
        URI="500InternErr.html";
        URI.prepend(WebFileFolderName); //放置网页的文件夹名
        file.setFileName(URI);
    }

    if(URI.toUpper().endsWith(".JPG")||URI.toUpper().endsWith(".JPEG"))
        httpReply.append(getHttpHeadJPG(httpBody.size()));
    else if(URI.toUpper().endsWith(".CSS"))
        httpReply.append(getHttpHeadCss(httpBody.size()));
    else
        httpReply.append(getHttpHeadHtml(httpBody.size()));

    httpReply.append("\r\n\r\n");
    httpReply.append(httpBody);
    return httpReply;
}

void WebClientSocket::initMembers()
{
    structStatLine.statusOK="HTTP/1.1 200 OK";
    structStatLine.statusBadRequest="HTTP/1.1 400 Bad Request";
    structStatLine.statusNotFound="HTTP/1.1 404 Not Found";
    structStatLine.statusInternalServerError="HTTP/1.1 500 Internal Server Error";

    structContentType.contentHTML="Content-Type: text/html;charset=UTF-8";
    structContentType.contentJPG="Content-Type: image/jpeg";

    QByteArray bodyBadRequest="<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"
            "<html><head> <title>400 Bad Request</title> </head><body>"
            "<h1>Bad Request</h1><p>Your browser sent a request that this server could not understand.<br />"
            "</p></body></html>";
    structHttpByteArray.replyBadRequest=structStatLine.statusBadRequest;
    structHttpByteArray.replyBadRequest.append("\r\n");
    structHttpByteArray.replyBadRequest.append(getHttpHeadHtml(bodyBadRequest.size()));
    structHttpByteArray.replyBadRequest.append("\r\n\r\n");
    structHttpByteArray.replyBadRequest.append(bodyBadRequest);

}

QByteArray WebClientSocket::getHttpHeadHtml(qint32 contentLength)
{
    QByteArray httpHead="Server: Web Server of Things\r\nConnection: Keep-Alive\r\n"
            "Content-Length: "+QByteArray::number(contentLength)+"\r\n"
            "Content-Type: text/html;charset=UTF-8";
    return httpHead;
}

QByteArray WebClientSocket::getHttpHeadCss(qint32 contentLength)
{
    QByteArray httpHead="Server: Web Server of Things\r\nConnection: Keep-Alive\r\n"
            "Content-Length: "+QByteArray::number(contentLength)+"\r\n"
            "Content-Type: text/css;charset=GBK";
    return httpHead;
}

QByteArray WebClientSocket::getHttpHeadJPG(qint32 contentLength)
{
    QByteArray httpHead="Server: Web Server of Things\r\nConnection: Keep-Alive\r\n"
            "Content-Length: "+QByteArray::number(contentLength)+"\r\n"
            "Content-Type: image/jpeg";
    return httpHead;
}

WebClientSocket::~WebClientSocket()
{
   // qDebug()<<"One WebClientSocket deleted";
}
